package com.dong8.util;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

/**
 * @author tj
 */
public class DBControl
{
	private SQLiteDatabase g_easy_do_db = null;
	
	public DBControl(Context context)
	{
		OpenDataBase(context);
	}
	
	public boolean OpenDataBase(Context context)
	{
		if(g_easy_do_db == null) 
		{
			g_easy_do_db = context.openOrCreateDatabase(
					Environment.getExternalStorageDirectory().getAbsolutePath() + "/mayer/mayer.db", Context.MODE_PRIVATE, null);
		}
		
		LocalExecuteUpdate("CREATE TABLE IF NOT EXISTS check_results (id integer primary key autoincrement," +
				"sample_id text,check_date text,check_time text," +
				"date0 integer,date1 integer,date2 integer,date3 integer,v0 integer,v1 integer, v2 integer,v3 integer,r0 text,r1 text)");

		return true;
	}
   
	public boolean GetDataFromLocalDB(ArrayList<JSONObject> array,String sql)
	{
		Cursor result = g_easy_do_db.rawQuery(sql,null);
		int count = result.getColumnCount();
		while(result.moveToNext())
		{
			JSONObject obj = new JSONObject();
			for(int i = 0; i < count; i++)
			{
				try
				{
					String key = result.getColumnName(i);
					obj.put(key, result.getString(i));
				} 
				catch (JSONException e) 
				{
					e.printStackTrace();
				}
			}
	       		
			array.add(obj);
		}
	       
		result.close();   
		return true;
	}
	
	public boolean GetDataFromLocalDB2Dictionary(JSONObject obj,String sql)
	{
		Cursor result = g_easy_do_db.rawQuery(sql,null);
   		int count = result.getColumnCount();
   	
   		if(result.getCount() == 1)
  	 	{
   			result.moveToFirst();
   			for(int i = 0; i < count; i++)
   			{
   				String key = result.getColumnName(i);
   				try 
   				{
   					obj.put(key, result.getString(i));
				}
   				catch (JSONException e) 
   				{
   					e.printStackTrace();
   				}
   			}
  	 	}
       
   		result.close();  
   		return true;
	}
	
	public String GetSelectStringByKey(String sql)
	{
		String res = "";
		Cursor result = g_easy_do_db.rawQuery(sql,null);
		if(result.getCount() > 0)
		{
			result.moveToFirst();
			res = result.getString(0);
		}
		
		result.close();
		return res;
	}
	
	public boolean LocalExecuteUpdate(String sql)
	{
		g_easy_do_db.execSQL(sql);
		return true;
	}
}